package com.dsg.service.account.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.dsg.common.util.UUIDGenerator;
import com.dsg.common.util.toolbox.CollectionUtil;
import com.dsg.dao.account.DsgAccountAdjMapper;
import com.dsg.dao.account.DsgAccountAdjSubMapper;
import com.dsg.dao.account.DsgAccountTradeMapper;
import com.dsg.entity.account.DsgAccountAdj;
import com.dsg.entity.account.DsgAccountAdjSub;
import com.dsg.entity.account.DsgAccountTrade;
import com.dsg.entity.system.DsgSysFile;
import com.dsg.service.DsgServiceImpl;
import com.dsg.service.account.IDsgAccountAdjService;
import com.dsg.service.system.IDsgSysFileService;
import com.dsg.util.ExcelIteratorReader;
import com.dsg.util.RRException;
import com.dsg.util.SnowflakeKeyWorker;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.math.BigDecimal;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * <p>
 * 費用調整 服务实现类
 * </p>
 *
 * @author system
 * @since 2020-11-25
 */
@Service
@Slf4j
public class DsgAccountAdjServiceImpl extends DsgServiceImpl<DsgAccountAdjMapper, DsgAccountAdj> implements IDsgAccountAdjService {

    @Autowired
    private DsgAccountTradeMapper dsgAccountTradeMapper;
    @Autowired
    private DsgAccountAdjSubMapper dsgAccountAdjSubMapper;
    @Autowired
    private IDsgSysFileService dsgSysFileService;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void addDsgAccountAdj(DsgAccountAdj dsgAccountAdj, MultipartFile[] files) {
        if (files.length < 1) {
            throw new RRException("附件不能為空！");
        }
        QueryWrapper<DsgAccountTrade> queryWrapper = new QueryWrapper<>();
        switch (dsgAccountAdj.getAdjType()) {
            case DsgAccountAdj.ADJ_TYPE_1:
                queryWrapper.in("OID", dsgAccountAdj.getTradeOids());
                break;
            default:
                DsgAccountAdj queryAdj = new DsgAccountAdj();
                queryAdj.setApprStatus(DsgAccountAdj.APPR_STATUS_0);
                queryAdj.setTradeOids(dsgAccountAdj.getTradeOids());
                List<DsgAccountAdjSub> dsgAccountAdjSubList = baseMapper.selectDsgAccountAdjSubList(queryAdj);
                if (CollectionUtil.isNotEmpty(dsgAccountAdjSubList)){
                    throw new RRException("存在調整費用申請,審批通過後才能再次調整!");
                }
                List<DsgAccountTrade> dsgAccountTradeList = dsgAccountTradeMapper.selectTradeAdjList(dsgAccountAdj.getTradeOids());
                if (CollectionUtil.isNotEmpty(dsgAccountTradeList)) {
                    Map<String, List<DsgAccountTrade>> cardNoMap = dsgAccountTradeList.stream().collect(Collectors.groupingBy(I -> I.getCardNo()));
                    if (cardNoMap.size() > 1) {
                        throw new RRException("請選擇相同的咭卡!");
                    }
                    DsgAccountTrade dat = dsgAccountTradeList.get(0);
                    BigDecimal adjAmount;
                    if (dat.getAdjAmount() != null) {
                        adjAmount = dat.getTraAmount().subtract(dat.getAdjAmount());
                    } else {
                        adjAmount = dat.getTraAmount();
                    }
                    if (dsgAccountAdj.getAdjAmount().compareTo(adjAmount) > 0) {
                        throw new RRException("調整金額不能大於交易金額!");
                    } else {
                        dsgAccountAdj.setOid(UUIDGenerator.getUUID());
                        dsgAccountAdj.setAdjCode(SnowflakeKeyWorker.nextStrId());
                        dsgAccountAdj.setApprStatus(DsgAccountAdj.APPR_STATUS_0);
                        baseMapper.insert(dsgAccountAdj);
                        DsgAccountAdjSub dsgAccountAdjSub = new DsgAccountAdjSub();
                        dsgAccountAdjSub.setOid(UUIDGenerator.getUUID());
                        dsgAccountAdjSub.setPid(dsgAccountAdj.getOid());
                        dsgAccountAdjSub.setDataType(DsgAccountAdjSub.DATA_TYPE_2);
                        dsgAccountAdjSub.setDataId(dsgAccountAdj.getTradeOids());
                        dsgAccountAdjSub.setAdjAmount(dsgAccountAdj.getAdjAmount());
                        dsgAccountAdjSubMapper.insert(dsgAccountAdjSub);
                        DsgAccountTrade dsgAccountTrade = dsgAccountTradeMapper.selectById(dsgAccountAdj.getTradeOids());
                        if (dsgAccountTrade != null) {
                            dsgAccountTrade.setCostAdjTimes(dsgAccountTrade.getCostAdjTimes() == null ? 0 : dsgAccountTrade.getCostAdjTimes().intValue() + 1);
                        }
                        dsgAccountTradeMapper.updateById(dsgAccountTrade);
                        for (MultipartFile multipartFile : files) {
                            try {
                                File file = ExcelIteratorReader.multipartToFile(multipartFile);
                                dsgSysFileService.saveFile(new DsgSysFile(), file, dsgAccountAdj.getOid(), file.getName().substring(file.getName().lastIndexOf("."), file.getName().length()));
                            } catch (Exception e) {
                                log.error("保存附件異常:", e);
                                throw new RRException("保存附件異常!");
                            }
                        }
                    }
                }
                break;
        }
    }
}
